import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import * as requestIp from 'request-ip';
import { FrontRequestLogService } from "../modules/frontRequestLog/front-request-log.service";
import { FrontRequestLogEntity } from "../modules/frontRequestLog/front-request-log.entity";

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
    constructor(private readonly frontRequestLogService: FrontRequestLogService) { }

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        console.log('Before...');
        const args = context.getArgs();
        const url = args[0].url;
        const method = args[0].method;
        const body = args[0].body;
        const params = args[0].params;
        const clientIp = requestIp.getClientIp(context.getArgByIndex(1).req);
        let logReq = new FrontRequestLogEntity();
        logReq.body = JSON.stringify(body);
        logReq.url = url;
        logReq.ipAddress = clientIp;
        logReq.method = method;
        logReq.params = JSON.stringify(params);
        logReq.userId = args[0].body.userId


        console.log(`request clientIp:${clientIp} url:${url}, method:${method},params:${JSON.stringify(params)},body:${JSON.stringify(body)}`)
        const whitelist = [
            "/api-v1/deliveryAddress/queryAll",
        ];

        
        const now = Date.now();
        return next
            .handle()
            .pipe(
                tap((e) => {
                    console.log(e)
                    console.log(`After... ${Date.now() - now}ms`)
                    logReq.result = JSON.stringify(e);
                    if (!whitelist.includes(url)) {
                        console.log(`request clientIp:${clientIp} url:${url}, method:${method},params:${JSON.stringify(params)},body:${JSON.stringify(body)}`);
                        this.frontRequestLogService.add(logReq)
                    } else {
                        console.log(`Skipping log for whitelisted URL: ${url}`);
                    }
                }),
            );
    }
}